<?php
/*
 * @Descripttion: 
 * @version: 
 * @Author: siebe
 * @Date: 2022-02-15 21:47:20
 * @LastEditors: siebe
 * @LastEditTime: 2022-02-17 01:12:46
 */
declare (strict_types = 1);

namespace app\admin\controller;

use app\admin\exception\UserException;
use app\admin\validate\UserValidate;
use app\admin\model\SystemConfig;
use app\admin\model\SystemUser;
use think\Request;
use think\facade\Session;
use think\facade\View;

class Login
{
    //
    public function index(){
        $config = SystemConfig::getBaseConfig();
        View::assign([
            'config' => $config
        ]);
        return View::fetch();
    }
    public function login(Request $request){
        (new UserValidate())->goCheck('login');
        $data = $request->param();
        $user = SystemUser::getUserByUsername($data['username']);
        if(!$user){
            throw new UserException([
                'code' => 404,
                'msg' => '用户不存在',
                'errorCode' => 10102
            ]);
        }
        if($user->password != md5($data['password'].$user->key)){
            throw new UserException([
                'msg' => '用户密码错误',
                'errorCode' => 10104
            ]);
        }
        //version 6.0.12LTS中session前缀不生效
        //手动添加前缀防止与前台应用共享数据
        Session::set('admin_id',$user->id);
        //用户登录记录
        $user->allowField(['login_times', 'login_ip','last_time'])
            ->save([
                'login_times' => $user->login_times + 1,
                'login_ip' => $request->ip(),
                'last_time' => time()
            ]);
        return json([
            'msg' => '登录成功',
            'error_code' => 0
        ],200);
    }
    public function logout(){
        Session::delete('admin_id');
        return json([
            'msg' => '退出成功',
            'error_code' => 0
        ],200);
    }
}
